import {LocModel} from "../../../base/LocModel";
import {IRectAdapter} from "../../adapterInterface/model2/IRectAdapter";
import Configer from "../../../config/Configer";
import {FinalKey} from "../../../../../constant/FinalConstant";
import {Logger} from "../../../config/Logger";
import {GlobalModel} from "../../../adapterModel/model1/GlobalModel";
import {GlobalAdapter} from "../model1/GlobalAdapter";
import {globalAdapter} from "../../adapterInterface/model1/IGlobalAdapter";

export interface RectRecord {
  rect: any;
  region: any;
}

export const rectMap: { [key: string]: string } = {}

export class RectAdapter implements IRectAdapter {

  createHandle(id: string): RectRecord {
    const ret: RectRecord = { rect: undefined, region: undefined };
    let rect
    const allMap = Configer.getFinal(FinalKey.allMapRect);
    if (allMap === id) {
      rect = GetEntireMapRect();
    } else {
      const newName = `gg_rct_${id}`;
      rect = globals[newName] as rect;
    }
    if (rect) {
      ret.rect = rect;
      const region = CreateRegion();
      RegionAddRect(region, rect);
      ret.region = region;
      const regionId = globalAdapter.adapter.getHandleId(region);
      rectMap[regionId] = id;
      return ret;
    }
  }

  destroy(handle: RectRecord): void {
    handle_unref(handle.rect);
    RemoveRect(handle.rect);
    const region = handle.region;
    if (region) {
      const regionId = GetHandleId(region);
      rectMap[regionId] = undefined;
      handle_unref(region);
      RemoveRegion(region);
    }
  }

  enumDestructables(handle: RectRecord, actionFunc: (this: void) => void): void {
    EnumDestructablesInRect(handle.rect, null, actionFunc);
  }

  enumItems(handle: RectRecord, actionFunc: (this: void) => void): void {
    EnumItemsInRect(handle.rect, null, actionFunc);
  }

  getCenterLocModel(handle: RectRecord): LocModel {
    if (this.isValid(handle)) {
      const x = GetRectCenterX(handle.rect);
      const y = GetRectCenterY(handle.rect);
      const loc =  new LocModel(x, y)
      return loc;
    }
    return new LocModel(0, 0)
  }

  getRandomLocModel(handle: RectRecord): LocModel {
    if (this.isValid(handle)) {
      const location = GetRandomLocInRect(handle.rect);
      const loc =  new LocModel(GetLocationX(location), GetLocationY(location))
      RemoveLocation(location);
      return loc;
    }
    return new LocModel(0, 0)
  }

  bindHandle(handle: RectRecord): void {
    handle_ref(handle.rect);
    handle_ref(handle.region);
  }

  equal(handle1: RectRecord, handle2: RectRecord): boolean {
    return (GetHandleId(handle1.rect) === GetHandleId(handle2.rect))
  }

  isValid(handle: RectRecord): boolean {
    if (handle.rect) {
      return true;
    }
    return false;
  }
}
